package com.service.approval.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.service.approval.controller.dto.ApprovalResult;
import com.service.approval.localthread.ApprovalThreadLocal;
import com.service.approval.model.ApprovalInfo;
import com.service.approval.model.InsuredInfo;
import com.service.approval.model.ProductInfo;
import com.service.approval.service.ApprovalService;
import com.service.approval.service.InsurancePolicyService;
import com.service.approval.service.ProductService;
import com.service.approval.util.DateFormatUtil;
import com.service.approval.valuedata.DistributerProduct;
import com.service.approval.valuedata.InsurancePolicy;

@Service
public class ApprovalServiceImpl implements ApprovalService{

	@Autowired
	private ProductService productService;
	@Autowired
	private InsurancePolicyService insurancePolicyService;
	
	@Override
	public ApprovalResult approval(ApprovalInfo approvalInfo) {
		//核保参数检查
		approvalInfo.check();
		ApprovalThreadLocal.set(approvalInfo);
		//产品是否存在
		DistributerProduct distributerProduct = productService.findDistributerProductByJbProductCode(approvalInfo.getProductInfo().getProductCode());
		if (distributerProduct == null) {
			//TODO
		}
		//该渠道是否有销售该产品的权限
		//创建保单记录
		String orderNo = String.valueOf(System.currentTimeMillis());
		ProductInfo productInfo = approvalInfo.getProductInfo();
		InsuredInfo insuredInfo = approvalInfo.getInsuredInfo();
		InsurancePolicy insurancePolicy = new InsurancePolicy(approvalInfo.getMerchantNo(), approvalInfo.getMerchantOrderNo(),orderNo , DateFormatUtil.strFormatDate(productInfo.getBeginTime(), DateFormatUtil.DATE_FORMAT),DateFormatUtil.strFormatDate(productInfo.getEndTime(), DateFormatUtil.DATE_FORMAT));
		insurancePolicy.buildProductInfo(productInfo.getProductName(), productInfo.getProductCode(), productInfo.getPlanName(), productInfo.getPlanCode(), productInfo.getPrice(), productInfo.getAmount(), distributerProduct.getCompanyName(), distributerProduct.getCompanyCode());
		Map<String, String> createPolicyResult = insurancePolicyService.createPolicy(insurancePolicy);
		ApprovalResult approvalResult = null;
		if (createPolicyResult.get("code").equals("0000")) {
			approvalResult = new ApprovalResult(true, createPolicyResult.get("msg"), approvalInfo.getMerchantOrderNo(), insuredInfo.getInsuredName(), createPolicyResult.get("jbPolicyNo"));
		}else {
			approvalResult = new ApprovalResult(false, createPolicyResult.get("msg"));
		}
		return approvalResult;
	}

}
